#include <iostream>
#include <sstream>
#include "utils/HardwareInfo.h"
#include "utils/Config.h"
#include <openssl/hmac.h>
#include <openssl/evp.h>

std::string hexEncode(const unsigned char* data, size_t len) {
    static const char* hex = "0123456789abcdef";
    std::string out; out.resize(len * 2);
    for (size_t i = 0; i < len; ++i) {
        out[2*i]   = hex[(data[i] >> 4) & 0xF];
        out[2*i+1] = hex[data[i] & 0xF];
    }
    return out;
}

std::string hmacSha256Hex(const std::string& key, const std::string& content) {
    unsigned char md[EVP_MAX_MD_SIZE];
    unsigned int md_len = 0;
    HMAC(EVP_sha256(), key.data(), static_cast<int>(key.size()),
         reinterpret_cast<const unsigned char*>(content.data()), content.size(), md, &md_len);
    return hexEncode(md, md_len);
}

std::string buildSignContent(const std::string& authType,
                            const std::string& deviceSn,
                            const std::string& deviceType,
                            const std::string& random,
                            int securemode) {
    std::ostringstream oss;
    oss << "authType" << authType
        << "deviceSn" << deviceSn
        << "deviceType" << deviceType
        << "random" << random
        << "securemode" << securemode;
    return oss.str();
}

int main() {
    std::string deviceSn = ems::utils::HardwareInfo::getDeviceId();
    std::string deviceType = "32764";
    std::string random = "79380248";
    int securemode = 2;
    std::string authType = "login";
    std::string deviceTypeSecret = "shkg_prod_plc_32764";
    
    std::string content = buildSignContent(authType, deviceSn, deviceType, random, securemode);
    std::string password = hmacSha256Hex(deviceTypeSecret, content);
    std::string username = deviceSn + "&" + deviceType;
    
    std::cout << "=== MQTT Authentication Debug ===" << std::endl;
    std::cout << "Device SN: " << deviceSn << std::endl;
    std::cout << "Device Type: " << deviceType << std::endl;
    std::cout << "Auth Type: " << authType << std::endl;
    std::cout << "Random: " << random << std::endl;
    std::cout << "Secure Mode: " << securemode << std::endl;
    std::cout << "Device Type Secret: " << deviceTypeSecret << std::endl;
    std::cout << "\nSign Content: " << content << std::endl;
    std::cout << "Username: " << username << std::endl;
    std::cout << "Password (HMAC-SHA256): " << password << std::endl;
    
    return 0;
}